# flask_video.py
import os
import subprocess
import threading
import logging
from flask import Flask, render_template, send_from_directory, jsonify, request

app = Flask(__name__, static_folder='static')

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# HLS 输出目录
HLS_OUTPUT_DIR = os.path.join(os.getcwd(), "hls_output")
os.makedirs(HLS_OUTPUT_DIR, exist_ok=True)

# RTSP 流地址
RTSP_STREAMS = {
    "main": "rtsp://192.168.1.18:554/ch01.264",
    "sub": "rtsp://192.168.1.18:554/ch01_sub.264"
}

# 全局变量存储当前进程
ffmpeg_process = None
current_stream = None


def stop_ffmpeg():
    global ffmpeg_process
    if ffmpeg_process and ffmpeg_process.poll() is None:
        logger.info("Stopping existing FFmpeg process...")
        ffmpeg_process.terminate()
        try:
            ffmpeg_process.wait(timeout=5)
        except subprocess.TimeoutExpired:
            logger.warning("FFmpeg did not terminate, killing it.")
            ffmpeg_process.kill()
        ffmpeg_process = None
        logger.info("FFmpeg stopped.")


def start_ffmpeg(stream_type):
    global ffmpeg_process, current_stream

    if current_stream == stream_type and ffmpeg_process and ffmpeg_process.poll() is None:
        logger.info(f"{stream_type} already running.")
        return True

    stop_ffmpeg()

    rtsp_url = RTSP_STREAMS.get(stream_type)
    if not rtsp_url:
        logger.error(f"Invalid stream type: {stream_type}")
        return False

    output_file = os.path.join(HLS_OUTPUT_DIR, f"{stream_type}_stream.m3u8")

    # 清理旧文件
    for f in os.listdir(HLS_OUTPUT_DIR):
        if f.startswith(stream_type):
            os.remove(os.path.join(HLS_OUTPUT_DIR, f))

    command = [
        "ffmpeg",
        "-rtsp_transport", "tcp",
        "-i", rtsp_url,
        "-c:v", "copy",
        "-c:a", "aac",
        "-f", "hls",
        "-hls_time", "2",
        "-hls_list_size", "3",
        "-hls_flags", "delete_segments+round_durations",
        "-hls_allow_cache", "0",
        "-hls_segment_type", "mpegts",
        output_file
    ]

    logger.info(f"Starting FFmpeg: {' '.join(command)}")

    try:
        ffmpeg_process = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True
        )

        def log_output():
            while True:
                line = ffmpeg_process.stdout.readline()
                if not line and ffmpeg_process.poll() is not None:
                    break
                if line:
                    logger.info(f"[FFmpeg] {line.strip()}")

        threading.Thread(target=log_output, daemon=True).start()
        current_stream = stream_type
        return True
    except Exception as e:
        logger.error(f"Error starting FFmpeg: {e}")
        return False


@app.route('/')
def index():
    return render_template("index.html")


@app.route('/switch_stream/<stream_type>')
def switch_stream(stream_type):
    success = start_ffmpeg(stream_type)
    if success:
        return jsonify({"status": "success", "stream": stream_type})
    else:
        return jsonify({"status": "error", "message": "Failed to start stream"}), 500


@app.route('/hls/<filename>')
def hls_files(filename):
    return send_from_directory(HLS_OUTPUT_DIR, filename)


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=False)
